<template>
  <div style="width: 100%">
    <div class="content">
      <img src="../assets/logo.png" class="logo" />
    </div>

    <h2>希望小帮手 Hope helper</h2>
    <van-form @submit="login" id="form">
      <van-field
        v-model="phone"
        maxlength="11"
        name="手机号"
        label="手机号"
        placeholder="手机号"
        :formatter="numFormatter"
        :rules="[{ required: true, message: '请填写手机号' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :formatter="trimFormatter"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div class="register">
        <span @click="$router.replace('/register')">立即注册</span>
      </div>
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >登陆</van-button
        >
      </div>
    </van-form>
    <van-overlay :show="isLogin">
      <div class="loading">加载中...<van-loading /></div>
    </van-overlay>
  </div>
</template>
<script>
import { Notify } from 'vant';
export default {
  name: "LoginPage",
  data() {
    return {
      phone: "",
      password: "",
      isLogin: false,
    };
  },
  methods: {
    trimFormatter(value) {
        return value.replace(' ', '');
    },
    login() {
      if (!/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(this.phone)) {
        this.$dialog.alert({
          message: "请输入正确的手机号",
        });
        return;
      }
      this.isLogin = true;

      this.postRequest("/user/login", {
        phone: this.phone,
        password: this.password,
      }).then((result) => {
        this.isLogin = false;
        if (result.data.status == 200) {
          localStorage.setItem("loginUser", JSON.stringify(result.data.data));
          localStorage.setItem("tokenName", result.data.data.tokenName);
          localStorage.setItem("tokenValue", result.data.data.tokenValue);
          Notify({ type: 'success', message: '登陆成功' });
          this.$router.replace('/index');
        }
      });
    },
    numFormatter(value) {
      // 过滤输入的数字
      return value.replace(/[^\d]/g, '');
    },
  },
  created(){
    let user = localStorage.getItem("loginUser")
    if(user != undefined) {
      this.$router.replace('/index')
    }
  }
};
</script>
<style scoped>
.logo {
  width: 60%;
  margin: auto;
}
h2 {
  text-align: center;
  font-family: FangSong;
}
.content {
  width: 80%;
  margin: auto;
  text-align: center;
}
.register {
  color: #a6e3e9;
  margin-top: 5%;
  width: 95%;
  text-align: right;
}
.loading {
  width: 100%;
  text-align: center;
  margin-top: 80%;
  color: #fff;
}
#form{
  margin-top: 10%;
}
</style>
